package com.mzy.linear_struct.hot100.链表;

/**
 * @Author: mizy3
 * @Date: 2024/08/20/下午7:07
 * @Description:
 */
public class Pro61旋转链表 {

    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) return null;
        if (head.next == null) return head;
        int len = 0;
        ListNode cur = head;
        ListNode tail = null;
        while (cur != null) {
            tail = cur;
            cur = cur.next;
            len++;
        }
        k = k % len;

        if (k == 0) return head;
        cur = head;
        // 1 2 3 4 5
        // 4 5 1 2 3
        // 这里不能用k，必须用len-k-1
        int p = len - k - 1;
        while (p > 0) {
            cur = cur.next;
            p--;
        }

        ListNode rotate = cur.next;
        cur.next = null;
        tail.next = head;

        return rotate;
    }
}
























